package log

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"path/filepath"
	"strings"
)

// MyFormatter 自定义的日志格式化器
type MyFormatter struct {
}

func (m MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}

	timestamp := entry.Time.Format("2006-01-02 15:04:05")
	var newLog string

	//HasCaller()为true才会有调用信息
	if entry.HasCaller() {
		newLog = fmt.Sprintf("[%s] [%s] [%s] %s\n",
			colorTimeStamp(timestamp), colorLevel(entry), colorCaller(entry), entry.Message)
	} else {
		newLog = fmt.Sprintf("[%s] [%s] %s\n", colorTimeStamp(timestamp), colorLevel(entry), entry.Message)
	}

	b.WriteString(newLog)
	return b.Bytes(), nil
}

func colorCaller(entry *logrus.Entry) string {
	fName := filepath.Base(entry.Caller.File)
	line := entry.Caller.Line
	return Green(fmt.Sprintf("%s:%d", fName, line))
}

func colorTimeStamp(str string) string {
	return Gray(str)
}

func colorLevel(entry *logrus.Entry) string {
	str := strings.ToUpper(entry.Level.String())
	switch entry.Level {
	case logrus.ErrorLevel:
		return Red(str)
	case logrus.WarnLevel:
		return Yellow(str)
	default:
		return Blue(str)
	}
}
